<template>
  <div class="my-articles-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">我的文章</h1>
          <p class="page-subtitle">管理您发布的所有文章</p>
        </div>
      </div>
    </div>

    <!-- 筛选器 -->
    <div class="filter-section">
      <el-card class="filter-card" shadow="never">
        <div class="filter-content">
          <div class="filter-tabs">
            <el-radio-group
              v-model="currentStatus"
              @change="handleStatusChange"
            >
              <el-radio-button :value="undefined">全部</el-radio-button>
              <el-radio-button :value="1">已发布</el-radio-button>
              <el-radio-button :value="0">草稿</el-radio-button>
              <el-radio-button :value="5">已下架</el-radio-button>
              <el-radio-button :value="2">已删除</el-radio-button>
            </el-radio-group>
          </div>
          <div class="filter-actions">
            <el-button @click="handleRefresh">
              <IconifyIconOnline icon="ep:refresh" />
              刷新
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 文章列表 -->
    <div class="articles-section">
      <div v-loading="loading" class="articles-grid">
        <div v-for="article in articles" :key="article.id" class="article-card">
          <el-card class="card-content" shadow="hover">
            <!-- 文章封面 -->
            <div class="article-cover">
              <el-image
                v-if="article.coverImage"
                :src="article.coverImage"
                fit="cover"
                class="cover-image"
                @error="handleImageError"
              />
              <div v-else class="default-cover">
                <IconifyIconOnline icon="ep:document" />
              </div>
            </div>

            <!-- 文章信息 -->
            <div class="article-info">
              <div class="article-header">
                <h3 class="article-title" @click="handleViewArticle(article)">
                  {{ article.title }}
                </h3>
                <div class="article-status">
                  <el-tag
                    :type="getStatusType(article.status)"
                    size="small"
                    effect="plain"
                  >
                    {{ getStatusText(article.status) }}
                  </el-tag>
                </div>
              </div>

              <p class="article-summary">
                {{ article.summary || "暂无摘要" }}
              </p>

              <div class="article-meta">
                <div class="meta-left">
                  <span class="meta-item">
                    <IconifyIconOnline icon="ep:view" />
                    {{ article.viewCount || 0 }}
                  </span>
                  <span class="meta-item">
                    <IconifyIconOnline icon="ep:chat-dot-round" />
                    {{ article.commentCount || 0 }}
                  </span>
                  <span class="meta-item">
                    <IconifyIconOnline icon="ep:star" />
                    {{ article.likeCount || 0 }}
                  </span>
                </div>
                <div class="meta-right">
                  <span class="publish-time">
                    {{ formatTime(article.publishTime || article.createTime) }}
                  </span>
                </div>
              </div>

              <!-- 标签 -->
              <div
                v-if="article.tags && article.tags.length > 0"
                class="article-tags"
              >
                <el-tag
                  v-for="tag in article.tags.slice(0, 3)"
                  :key="tag.id"
                  :color="tag.color"
                  size="small"
                  effect="plain"
                  class="tag-item"
                  style="color: #fff"
                >
                  {{ tag.name }}
                </el-tag>
                <span v-if="article.tags.length > 3" class="more-tags">
                  +{{ article.tags.length - 3 }}
                </span>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="article-actions">
              <el-button-group size="small">
                <el-tooltip content="编辑" placement="top">
                  <el-button @click="handleEditArticle(article)">
                    <IconifyIconOnline icon="ep:edit" />
                  </el-button>
                </el-tooltip>
                <el-tooltip content="查看" placement="top">
                  <el-button @click="handleViewArticle(article)">
                    <IconifyIconOnline icon="ep:view" />
                  </el-button>
                </el-tooltip>
                <!-- 草稿状态：显示发布按钮 -->
                <el-tooltip
                  v-if="article.status === 0"
                  content="发布"
                  placement="top"
                >
                  <el-button
                    type="primary"
                    @click="handlePublishDraft(article)"
                  >
                    <IconifyIconOnline icon="ep:upload" />
                  </el-button>
                </el-tooltip>
                <!-- 已发布状态：显示下架按钮 -->
                <el-tooltip
                  v-if="article.status === 1"
                  content="下架"
                  placement="top"
                >
                  <el-button
                    type="warning"
                    @click="handleWithdrawArticle(article)"
                  >
                    <IconifyIconOnline icon="ep:download" />
                  </el-button>
                </el-tooltip>
                <!-- 已下架状态：显示重新发布按钮 -->
                <el-tooltip
                  v-if="article.status === 5"
                  content="重新发布"
                  placement="top"
                >
                  <el-button
                    type="success"
                    @click="handleRepublishArticle(article)"
                  >
                    <IconifyIconOnline icon="ep:upload" />
                  </el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button
                    type="danger"
                    @click="handleDeleteArticle(article)"
                  >
                    <IconifyIconOnline icon="ep:delete" />
                  </el-button>
                </el-tooltip>
              </el-button-group>
            </div>
          </el-card>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && articles.length === 0" class="empty-state">
          <el-empty description="暂无文章">
            <template #image>
              <IconifyIconOnline
                icon="ep:document"
                style="font-size: 64px; color: #ddd"
              />
            </template>
            <template #description>
              <p>您还没有发布任何文章</p>
              <p>点击右上角"写文章"按钮开始创作吧！</p>
            </template>
            <el-button type="primary" @click="handleCreateArticle">
              立即创作
            </el-button>
          </el-empty>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="articles.length > 0" class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOnline } from "@/components/ReIcon";
import {
  getMyArticleListApi,
  deleteMyArticleApi,
  publishDraftApi,
  withdrawArticleApi,
  type ArticlePublishResponse,
  type MyArticleListQuery
} from "@/api/user-article";

defineOptions({
  name: "MyArticles"
});

// 路由
const router = useRouter();

// 响应式数据
const loading = ref(false);
const articles = ref<ArticlePublishResponse[]>([]);
const currentStatus = ref<number | undefined>(undefined);

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

// 初始化
onMounted(() => {
  loadArticles();
});

// 加载文章列表
const loadArticles = async () => {
  try {
    loading.value = true;
    console.log("📚 开始加载文章列表...", {
      status: currentStatus.value,
      current: pagination.current,
      size: pagination.size
    });

    const params: MyArticleListQuery = {
      status: currentStatus.value,
      current: pagination.current,
      size: pagination.size
    };

    const response = await getMyArticleListApi(params);
    console.log("📝 API响应:", response);

    if (response.code === 200) {
      articles.value = response.data || [];

      // 根据后端响应格式调整分页信息
      if (Array.isArray(response.data)) {
        pagination.total = response.data.length;
      } else if (response.data && typeof response.data === "object") {
        // 如果后端返回的是分页对象
        articles.value = response.data.records || response.data.list || [];
        pagination.total = response.data.total || 0;
      }

      console.log("✅ 文章列表加载成功", {
        count: articles.value.length,
        total: pagination.total
      });
    } else {
      console.warn("⚠️ API返回错误:", response);
      ElMessage.error(response.message || "加载文章列表失败");
    }
  } catch (error) {
    console.error("❌ 加载文章列表失败:", error);

    // 更详细的错误处理
    let errorMessage = "加载文章列表失败";
    if (error?.response?.status === 401) {
      errorMessage = "登录已过期，请重新登录";
    } else if (error?.response?.status === 403) {
      errorMessage = "没有权限访问";
    } else if (error?.response?.data?.message) {
      errorMessage = error.response.data.message;
    } else if (error?.message) {
      errorMessage = error.message;
    }

    ElMessage.error(errorMessage);
  } finally {
    loading.value = false;
  }
};

// 状态变化处理
const handleStatusChange = () => {
  pagination.current = 1;
  loadArticles();
};

// 刷新
const handleRefresh = () => {
  loadArticles();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  loadArticles();
};

const handleCurrentChange = (current: number) => {
  pagination.current = current;
  loadArticles();
};

// 获取状态类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0:
      return "info"; // 草稿
    case 1:
      return "success"; // 已发布
    case 2:
      return "danger"; // 已删除
    case 3:
      return "warning"; // 待审核
    case 4:
      return "danger"; // 审核拒绝
    case 5:
      return "warning"; // 已下架
    default:
      return "info";
  }
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return "草稿";
    case 1:
      return "已发布";
    case 2:
      return "已删除";
    case 3:
      return "待审核";
    case 4:
      return "审核拒绝";
    case 5:
      return "已下架";
    default:
      return "未知";
  }
};

// 格式化时间
const formatTime = (timeStr: string) => {
  if (!timeStr) return "";
  const date = new Date(timeStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  const minute = 60 * 1000;
  const hour = 60 * minute;
  const day = 24 * hour;

  if (diff < minute) {
    return "刚刚";
  } else if (diff < hour) {
    return Math.floor(diff / minute) + "分钟前";
  } else if (diff < day) {
    return Math.floor(diff / hour) + "小时前";
  } else {
    return date.toLocaleDateString();
  }
};

// 处理图片错误
const handleImageError = () => {
  // 图片加载失败时的处理
};

// 创建文章
const handleCreateArticle = () => {
  router.push("/user/article/publish");
};

// 编辑文章
const handleEditArticle = (article: ArticlePublishResponse) => {
  // 使用发布页面的编辑模式
  console.log("✏️ 编辑文章:", article.id);
  router.push(`/user/article/publish?id=${article.id}`);
};

// 查看文章
const handleViewArticle = (article: ArticlePublishResponse) => {
  // 跳转到文章详情页
  router.push(`/user/article/${article.id}`);
};

// 发布草稿
const handlePublishDraft = async (article: ArticlePublishResponse) => {
  try {
    await ElMessageBox.confirm(
      `确定要发布文章"${article.title}"吗？`,
      "确认发布",
      { type: "warning" }
    );

    console.log("🚀 开始发布草稿:", article.id);
    const response = await publishDraftApi(article.id);

    if (response.code === 200) {
      console.log("✅ 草稿发布成功");
      ElMessage.success("文章发布成功");
      loadArticles();
    } else {
      console.warn("⚠️ 发布失败:", response);
      ElMessage.error(response.message || "发布失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("❌ 发布草稿失败:", error);
      ElMessage.error("发布失败");
    }
  }
};

// 删除文章
const handleDeleteArticle = async (article: ArticlePublishResponse) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文章"${article.title}"吗？此操作不可恢复。`,
      "确认删除",
      { type: "warning" }
    );

    console.log("🗑️ 开始删除文章:", article.id);
    const response = await deleteMyArticleApi(article.id);

    if (response.code === 200) {
      console.log("✅ 文章删除成功");
      ElMessage.success("文章删除成功");
      loadArticles();
    } else {
      console.warn("⚠️ 删除失败:", response);
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("❌ 删除文章失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 下架文章
const handleWithdrawArticle = async (article: ArticlePublishResponse) => {
  try {
    await ElMessageBox.confirm(
      `确定要下架文章"${article.title}"吗？下架后外部用户将无法查看该文章。`,
      "确认下架",
      { type: "warning" }
    );

    console.log("📦 开始下架文章:", article.id);
    const response = await withdrawArticleApi(article.id);

    if (response.code === 200) {
      console.log("✅ 文章下架成功");
      ElMessage.success("文章下架成功");
      loadArticles();
    } else {
      console.warn("⚠️ 下架失败:", response);
      ElMessage.error(response.message || "下架失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("❌ 下架文章失败:", error);
      ElMessage.error("下架失败");
    }
  }
};

// 重新发布文章（已下架文章）
const handleRepublishArticle = async (article: ArticlePublishResponse) => {
  try {
    await ElMessageBox.confirm(
      `确定要重新发布文章"${article.title}"吗？`,
      "确认发布",
      { type: "warning" }
    );

    console.log("🚀 开始重新发布文章:", article.id);
    const response = await publishDraftApi(article.id);

    if (response.code === 200) {
      console.log("✅ 文章重新发布成功");
      ElMessage.success("文章重新发布成功");
      loadArticles();
    } else {
      console.warn("⚠️ 重新发布失败:", response);
      ElMessage.error(response.message || "重新发布失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("❌ 重新发布文章失败:", error);
      ElMessage.error("重新发布失败");
    }
  }
};
</script>

<style lang="scss" scoped>
// 响应式设计
@media (width <= 768px) {
  .my-articles-container {
    padding: 16px;

    .page-header {
      .header-content {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;

        .action-section {
          align-self: stretch;

          .el-button {
            width: 100%;
          }
        }
      }
    }

    .filter-section {
      .filter-card {
        .filter-content {
          flex-direction: column;
          gap: 16px;
          align-items: stretch;

          .filter-tabs {
            :deep(.el-radio-group) {
              display: flex;
              flex-wrap: wrap;
              gap: 8px;

              .el-radio-button {
                flex: 1;
                min-width: 80px;

                .el-radio-button__inner {
                  width: 100%;
                  text-align: center;
                }
              }
            }
          }
        }
      }
    }

    .articles-section {
      .articles-grid {
        grid-template-columns: 1fr;
        gap: 16px;

        .article-card {
          .card-content {
            .article-cover {
              height: 160px;
            }

            .article-info {
              padding: 16px;

              .article-header {
                .article-title {
                  font-size: 16px;
                }
              }
            }

            .article-actions {
              padding: 12px 16px;

              :deep(.el-button-group) {
                display: flex;
                justify-content: space-between;

                .el-button {
                  flex: 1;
                  margin-right: 8px;

                  &:last-child {
                    margin-right: 0;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

.my-articles-container {
  min-height: 100vh;
  padding: 20px;
  background: #f8f9fa;

  .page-header {
    margin-bottom: 24px;

    .header-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      max-width: 1200px;
      margin: 0 auto;

      .title-section {
        .page-title {
          margin: 0 0 8px;
          font-size: 32px;
          font-weight: 700;
          color: #1a1a1a;
        }

        .page-subtitle {
          margin: 0;
          font-size: 16px;
          color: #8c8c8c;
        }
      }

      .action-section {
        .el-button {
          padding: 12px 24px;
          font-size: 16px;
          font-weight: 500;
          background: #1890ff;
          border-color: #1890ff;
          border-radius: 8px;
          transition: all 0.3s ease;

          &:hover {
            background: #40a9ff;
            border-color: #40a9ff;
            box-shadow: 0 4px 12px rgb(24 144 255 / 30%);
            transform: translateY(-1px);
          }
        }
      }
    }
  }

  .filter-section {
    margin-bottom: 24px;

    .filter-card {
      max-width: 1200px;
      margin: 0 auto;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgb(0 0 0 / 6%);

      :deep(.el-card__body) {
        padding: 20px;
      }

      .filter-content {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .filter-tabs {
          :deep(.el-radio-group) {
            .el-radio-button {
              .el-radio-button__inner {
                margin-right: 8px;
                font-weight: 500;
                color: #595959;
                background: white;
                border: 1px solid #d9d9d9;
                border-radius: 8px;
                transition: all 0.2s ease;

                &:hover {
                  color: #1890ff;
                  background: #f0f8ff;
                  border-color: #1890ff;
                }
              }

              &.is-active {
                .el-radio-button__inner {
                  color: white;
                  background: #1890ff;
                  border-color: #1890ff;
                  box-shadow: 0 2px 4px rgb(24 144 255 / 20%);
                }
              }
            }
          }
        }

        .filter-actions {
          .el-button {
            color: #595959;
            border-color: #d9d9d9;
            border-radius: 8px;
            transition: all 0.2s ease;

            &:hover {
              color: #1890ff;
              background: #f0f8ff;
              border-color: #1890ff;
            }
          }
        }
      }
    }
  }

  .articles-section {
    max-width: 1200px;
    margin: 0 auto;

    .articles-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
      gap: 24px;
      margin-bottom: 32px;

      .article-card {
        .card-content {
          overflow: hidden;
          border: 1px solid #f0f0f0;
          border-radius: 12px;
          transition: all 0.3s ease;

          &:hover {
            box-shadow: 0 8px 24px rgb(0 0 0 / 12%);
            transform: translateY(-4px);
          }

          :deep(.el-card__body) {
            padding: 0;
          }

          .article-cover {
            position: relative;
            height: 200px;
            overflow: hidden;

            .cover-image {
              width: 100%;
              height: 100%;
              object-fit: cover;
              transition: transform 0.3s ease;

              &:hover {
                transform: scale(1.05);
              }
            }

            .default-cover {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 100%;
              height: 100%;
              font-size: 48px;
              color: white;
              background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
            }
          }

          .article-info {
            padding: 20px;

            .article-header {
              display: flex;
              align-items: flex-start;
              justify-content: space-between;
              margin-bottom: 12px;

              .article-title {
                flex: 1;
                margin: 0;
                margin-right: 12px;
                font-size: 18px;
                font-weight: 600;
                line-height: 1.4;
                color: #1a1a1a;
                cursor: pointer;
                transition: color 0.2s ease;

                &:hover {
                  color: #1890ff;
                }
              }

              .article-status {
                flex-shrink: 0;
              }
            }

            .article-summary {
              display: -webkit-box;
              margin: 0 0 16px;
              overflow: hidden;
              -webkit-line-clamp: 2;
              font-size: 14px;
              line-height: 1.5;
              color: #8c8c8c;
              -webkit-box-orient: vertical;
            }

            .article-meta {
              display: flex;
              align-items: center;
              justify-content: space-between;
              margin-bottom: 16px;
              font-size: 12px;
              color: #8c8c8c;

              .meta-left {
                display: flex;
                gap: 16px;

                .meta-item {
                  display: flex;
                  gap: 4px;
                  align-items: center;
                }
              }

              .meta-right {
                .publish-time {
                  font-size: 12px;
                }
              }
            }

            .article-tags {
              display: flex;
              flex-wrap: wrap;
              gap: 8px;
              align-items: center;

              .tag-item {
                font-size: 12px;
                border-radius: 4px;
              }

              .more-tags {
                font-size: 12px;
                color: #8c8c8c;
              }
            }
          }

          .article-actions {
            padding: 16px 20px;
            background: #fafafa;
            border-top: 1px solid #f0f0f0;

            :deep(.el-button-group) {
              .el-button {
                margin-right: 8px;
                color: #595959;
                border-color: #d9d9d9;
                border-radius: 6px;
                transition: all 0.2s ease;

                &:hover {
                  color: #1890ff;
                  background: #f0f8ff;
                  border-color: #1890ff;
                }

                &.el-button--primary {
                  color: white;
                  background: #1890ff;
                  border-color: #1890ff;

                  &:hover {
                    background: #40a9ff;
                    border-color: #40a9ff;
                  }
                }

                &.el-button--success {
                  color: white;
                  background: #52c41a;
                  border-color: #52c41a;

                  &:hover {
                    background: #73d13d;
                    border-color: #73d13d;
                  }
                }

                &.el-button--warning {
                  color: white;
                  background: #faad14;
                  border-color: #faad14;

                  &:hover {
                    background: #ffc53d;
                    border-color: #ffc53d;
                  }
                }

                &.el-button--danger {
                  &:hover {
                    color: #ff4d4f;
                    background: #fff2f0;
                    border-color: #ff4d4f;
                  }
                }
              }
            }
          }
        }
      }

      .empty-state {
        display: flex;
        grid-column: 1 / -1;
        align-items: center;
        justify-content: center;
        min-height: 400px;

        :deep(.el-empty) {
          .el-empty__description {
            p {
              margin: 8px 0;
              color: #8c8c8c;
            }
          }

          .el-button {
            margin-top: 16px;
            font-weight: 500;
            background: #1890ff;
            border-color: #1890ff;
            border-radius: 8px;

            &:hover {
              background: #40a9ff;
              border-color: #40a9ff;
            }
          }
        }
      }
    }

    .pagination-section {
      display: flex;
      justify-content: center;
      padding: 32px 0;

      :deep(.el-pagination) {
        .el-pager li {
          margin: 0 4px;
          border-radius: 6px;
          transition: all 0.2s ease;

          &:hover {
            color: #1890ff;
          }

          &.is-active {
            color: white;
            background: #1890ff;
          }
        }

        .btn-prev,
        .btn-next {
          margin: 0 4px;
          border-radius: 6px;
        }
      }
    }
  }
}
</style>
